import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/xindong_chat_singleton.dart';
import 'package:xindong/manager/xindong_user_controller.dart';
import 'package:xindong/models/gift/xindong_gift_class.dart';
import 'package:xindong/models/user/xindong_user.dart';
import 'package:xindong/utils/xindong_cache_util.dart';
import 'package:xindong/widgets/gift/model/xindong_gift_tab_class.dart';

// 类型定义
typedef XinDongSongLiSuccessFunction = void Function(XinDongGiftClass model, int count);

class XinDongLiWuType {
  static const int general = 0; // 普通礼物/活动礼物未知
  static const int backpack = 100; // 背包礼物，强制修改类型为100
}

class XinDongSongLiController extends GetxController {
  static XinDongSongLiController get to => Get.find();

  // 赠送对象
  late XinDongUser user;
  late XinDongSongLiSuccessFunction onSuccess;

  // 常规礼物列表(接口返回或者手动拼接模型)
  List<XinDongGiftTabClass> generalList = [];

  // 常规礼物
  TabController? generalTabController;

  // 当前选择礼物
  int selectCount = 1;
  XinDongGiftClass? selectGift;

  Future<List<XinDongGiftClass>> requestGiftList() async {
    var parameters = {"types": 1, "page": 1};
    final object = await XinDongNetworking.instance.request(
      "/api/gift/lists",
      method: XinDongHttpMethod.post,
      parameters: parameters,
    );
    if (object.code == XinDongServerStatus.success) {
      List list = object.data;
      final giftList = list.map((e) => XinDongGiftClass.fromJson(e)).toList();
      final one = XinDongGiftTabClass();
      one.type = 0;
      one.tabName = "礼物";
      one.list = giftList;
      // 添加到Tab数据
      generalList.clear();
      generalList.add(one);
      update();
      XinDongCacheSingleton.cacheGiftSVGA(giftList);
    }
    return [];
  }

  void onTapSend() async {
    // 没有选择的礼物
    if (selectGift == null) {
      showToast("请选择礼物");
      return;
    }
    final result = await XinDongChatSingleton.instance.requestSendGift(
      userId: user.uid,
      model: selectGift!,
      count: selectCount,
    );
    if (result) {
      onSuccess(selectGift!, selectCount);
      XinDongUserController.to.requestUserVolley();
    }
  }

  // 选择礼物（背包礼物暂时只能送1个）
  void onTapSelectClass(XinDongGiftClass model) {
    selectGift = model;
    if (model.cate_id == XinDongLiWuType.backpack) {
      selectCount = 1;
    }
    update();
  }

  // 数量改变
  void onSendCountChanged(int count) {
    if (count <= 0) {
      count = 1;
    }
    selectCount = count;
    update();
  }
}
